﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace Glucometer
{
    class XMLFileDumper
    {
        public static string FILE_NAME = "myXmlFile.xml";

        public static void SaveState(DeviceMemory memory, DeviceSettings settings, double BatteryLife)
        {
            try
            {
                string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml";
                FileStream fs = new FileStream(FILE_NAME, FileMode.Create);
                XmlTextWriter textWriter = new XmlTextWriter(fs,null);

                textWriter.WriteStartDocument();
                textWriter.WriteStartElement("STATE");

                //WRITE DOWN THE SETTINGS
                textWriter.WriteStartElement("SETTINGS");
                AddXMLElement("TEST_UNIT", settings.TestUnit.ToString(), textWriter);
                WriteXMLDateTime(settings.getDateTime(), textWriter);
                AddXMLElement("TIME_TICKS", settings.TickCount.ToString(), textWriter);
                textWriter.WriteEndElement(); //CLOSING SETTINGS

                textWriter.WriteStartElement("TEST_RESULTS");
                //NOW WRITE DOWN MEMORY
                foreach (TestRecord record in memory.RecordMemory)
                {
                    textWriter.WriteStartElement("TEST_RESULT");
                    AddXMLElement("TEST_VALUE", record.TestResultValue.ToString(), textWriter);
                    AddXMLElement("TEST_VALUE_UNIT", "DL", textWriter);
                    WriteXMLDateTime(record.TestDateTime, textWriter);
                    textWriter.WriteEndElement();
                }

                textWriter.WriteStartElement("BATTERY_LIFE");
                textWriter.WriteString(BatteryLife.ToString());
                textWriter.WriteEndElement(); //CLOSING BATTERY_LIFE

                textWriter.WriteEndElement(); //CLOSING TEST_RESULTS

                textWriter.WriteEndElement();// CLOSING STATE

                textWriter.WriteEndDocument();

                textWriter.Close();
            }
            catch { }
        }

        public static DeviceSettings GetSettingsFromXMLFile()
        {
            if (!File.Exists(FILE_NAME))
                return null;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(FILE_NAME);
                XmlNode stateNode = doc.ChildNodes[1];
                XmlNode settingsNode = stateNode.SelectSingleNode("//SETTINGS");
                if (settingsNode == null)
                    return null;
                int year = int.Parse(settingsNode.SelectSingleNode("//YEAR").FirstChild.Value);
                int month = int.Parse(settingsNode.SelectSingleNode("//MONTH").FirstChild.Value);
                int day = int.Parse(settingsNode.SelectSingleNode("//DAY").FirstChild.Value);
                int hour = int.Parse(settingsNode.SelectSingleNode("//HOUR").FirstChild.Value);
                int minute = int.Parse(settingsNode.SelectSingleNode("//MINUTE").FirstChild.Value);
                int time_ticks = int.Parse(settingsNode.SelectSingleNode("//TIME_TICKS").FirstChild.Value);
                DateTime dt = new DateTime(year, month, day, hour, minute, 0);
                TestUnit tu = TestUnit.L;
                if (settingsNode.SelectSingleNode("//TEST_UNIT").FirstChild.Value == "DL")
                {
                    tu = TestUnit.DL;
                }
                DeviceSettings settings = new DeviceSettings(2000);
                settings.LoadSetting(tu, dt, time_ticks);
                return settings;
            }
            catch { return null; }
        }

        public static void GetDeviceMemoryFromXMLFile(DeviceMemory memory)
        {            
            try
            {
                if (!File.Exists(FILE_NAME))
                    return;

                XmlDocument doc = new XmlDocument();
                doc.Load(FILE_NAME);
                XmlNode stateNode = doc.ChildNodes[1];
                XmlNode resultsNode = stateNode.SelectSingleNode("//TEST_RESULTS");
                XmlNodeList resultList = resultsNode.SelectNodes("/TEST_RESULT");
                foreach (XmlNode result in resultsNode)
                {
                    try
                    {
                        int testValue = int.Parse(result.SelectSingleNode("//TEST_VALUE").FirstChild.Value);
                        TestUnit tu = TestUnit.DL;
                        if (result.SelectSingleNode("//TEST_VALUE_UNIT").FirstChild.Value == "L")
                        {
                            tu = TestUnit.L;
                        }
                        int year = int.Parse(result.SelectSingleNode("//YEAR").FirstChild.Value);
                        int month = int.Parse(result.SelectSingleNode("//MONTH").FirstChild.Value);
                        int day = int.Parse(result.SelectSingleNode("//DAY").FirstChild.Value);
                        int hour = int.Parse(result.SelectSingleNode("//HOUR").FirstChild.Value);
                        int minute = int.Parse(result.SelectSingleNode("//MINUTE").FirstChild.Value);
                        DateTime dt = new DateTime(year, month, day, hour, minute, 0);
                        TestRecord record = new TestRecord(testValue, dt, tu);
                        memory.addRecord(record);
                    }
                    catch { }
                }
            }
            catch { }
        }

        private static void WriteXMLDateTime(DateTime dt, XmlTextWriter writer)
        {
            writer.WriteStartElement("DATE_TIME");

            AddXMLElement("YEAR", dt.Year.ToString(), writer);
            AddXMLElement("MONTH", dt.Month.ToString(), writer);
            AddXMLElement("DAY", dt.Day.ToString(), writer);
            AddXMLElement("HOUR", dt.Hour.ToString(), writer);
            AddXMLElement("MINUTE", dt.Minute.ToString(), writer);

            writer.WriteEndElement();
        }

        public static double GetBatteryLifeFromXMLFile()
        {
            try
            {
                if (!File.Exists(FILE_NAME))
                    return Glucometer.Utility.Battery.MAX_BATTERY_LIFE;

                XmlDocument doc = new XmlDocument();
                doc.Load(FILE_NAME);
                XmlNode stateNode = doc.ChildNodes[1];
                XmlNode resultsNode = stateNode.SelectSingleNode("//BATTERY_LIFE");

                double output = 0.0;
                if (double.TryParse(resultsNode.FirstChild.Value, out output))
                    return output;                
            }
            catch { }

            return Glucometer.Utility.Battery.MAX_BATTERY_LIFE;
        }

        private static void AddXMLElement(string nodename, string nodevalue, XmlTextWriter writer)
        {
            writer.WriteStartElement(nodename);
            writer.WriteString(nodevalue);
            writer.WriteEndElement();
        }
    }
}
